package com.tuocent.dagv2.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tuocent.dagv2.common.AjaxResult;
import com.tuocent.dagv2.common.utils.SnowFlakeID;
import com.tuocent.dagv2.constant.PublicConst;
import com.tuocent.dagv2.entity.FieldConfig;
import com.tuocent.dagv2.entity.FieldInfo;
import com.tuocent.dagv2.mapper.FieldConfigMapper;
import com.tuocent.dagv2.service.IFieldConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tuocent.dagv2.service.IFieldInfoService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.ui.Model;

import java.util.*;

/**
 * <p>
 * 字段配置 服务实现类
 * </p>
 *
 * @author Vincent
 * @since 2025-07-22
 */
@Service
public class FieldConfigServiceImpl extends ServiceImpl<FieldConfigMapper, FieldConfig> implements IFieldConfigService {
    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    private SnowFlakeID snowFlakeID;
    @Autowired
    private IFieldInfoService fieldInfoService;

    @Override
    public AjaxResult getFieldConfigList(Map<String, String> value) {
        String sort = value.containsKey("sort") ? value.get("sort") : "";
        QueryWrapper qw = new QueryWrapper<FieldConfig>();
        value.forEach((key, v) -> {
            if (!Arrays.asList(PublicConst.DEF_FIELD).contains(key) && !"sort".equals(key)) {
                qw.eq(key, v);
            }
        });
        switch (sort) {
            case "showList":
                qw.orderByAsc("show_idx");
            case "editList":
                qw.orderByAsc("edit_idx");
        }

        List<FieldConfig> data = list(qw);
        return AjaxResult.success(data);
    }

    @Override
    public AjaxResult getShowFieldList(String fillingModel, String classifyId) {
        List<FieldConfig> data = list(new QueryWrapper<FieldConfig>()
                .eq("classify_id", classifyId).eq("filling_model", fillingModel)
                .eq("is_showlist", "1")
                .orderByDesc("fixed_left").orderByAsc("show_idx"));
        return AjaxResult.success(data);
    }

    @Override
    public AjaxResult getFieldConfigData(String classifyId) {
        List<FieldConfig> fields;
        Map<String, String> recordMap = new LinkedHashMap<>();
        Map<String, String> filesMap = new LinkedHashMap<>();
        Map<String, String> projectMap = new LinkedHashMap<>();
        fields = list(new QueryWrapper<FieldConfig>()
                .eq("classify_id", classifyId)
                .orderByAsc("filling_model").orderByAsc("show_idx"));
        for (FieldConfig field : fields) {
            switch (field.getFillingModel()) {
                case "1":
                    recordMap.put(field.getFieldName(), field.getFieldTitle());
                    break;
                case "2":
                    filesMap.put(field.getFieldName(), field.getFieldTitle());
                    break;
                case "3":
                    projectMap.put(field.getFieldName(), field.getFieldTitle());
                    break;
            }
        }
        Map<String, Object> data = new HashMap<>();
        data.put("recordField", recordMap);
        data.put("fileField", filesMap);
        data.put("projectField", projectMap);
        return AjaxResult.success(data);
    }

    @Override
    public String setFieldConfig(Model model, String id, String classifyId, String fillingModel) {
        //获取字段配置
        List<FieldInfo> fieldInfos = fieldInfoService.list(new QueryWrapper<FieldInfo>()
                .eq("model", fillingModel).orderByAsc("idx"));

        FieldConfig data = getById(id);
        if (data == null) {
            data = new FieldConfig();
            data.setClassifyId(classifyId);
            data.setFillingModel(fillingModel);
            data.setIsShowlist("1");
            data.setShowWidth(100);
            data.setIsShowedit("1");
            data.setEditComponent("1");
        }
        model.addAttribute("fieldInfos", fieldInfos);
        model.addAttribute("data", data);
        return "/basic/setMetadata";
    }

    @Override
    public AjaxResult selectField(String classifyId, String fillingModel, String id, String value) {
        //检测字段是否已存在
        if (count(new QueryWrapper<FieldConfig>()
                .eq("classify_id", classifyId)
                .eq("filling_model", fillingModel)
                .eq("field_name", value)
                .ne("id", id)) > 0) {
            return AjaxResult.error("该字段已存在");
        }
        FieldInfo data = fieldInfoService.getOne(new QueryWrapper<FieldInfo>()
                .eq("model", fillingModel)
                .eq("name", value)
                .last("limit 1"));
        return data == null ? AjaxResult.error("没有找到该字段的信息") : AjaxResult.success(data);
    }

    @Override
    public AjaxResult saveFileConfig(FieldConfig data) {
        if ("".equals(data.getClassifyId()) || "".equals(data.getFillingModel())) {
            return AjaxResult.error("缺少必要的参数据");
        }
        if ("".equals(data.getFieldName())) {
            return AjaxResult.error("请选择需要的字段");
        }
        if (data.getDataLen() == null) {
            data.setDataLen(0);
        }
        if (data.getShowWidth() == null) {
            data.setShowWidth(80);
        }
        if ("".equals(data.getId())) {
            data.setId(snowFlakeID.getId());
            long count = this.count(new QueryWrapper<FieldConfig>()
                    .eq("classify_id", data.getClassifyId())
                    .eq("filling_model", data.getFillingModel()));
            data.setShowIdx((int) count);
            data.setEditIdx((int) count);
        }
        //检测字段是否已存在
        if (this.count(new QueryWrapper<FieldConfig>()
                .eq("classify_id", data.getClassifyId())
                .eq("filling_model", data.getFillingModel())
                .eq("field_name", data.getFieldName())
                .ne("id", data.getId())) > 0) {
            return AjaxResult.error("该字段已存在");
        }
        if ("1".equals(data.getIsOnly())) {
            if (this.count(new QueryWrapper<FieldConfig>()
                    .eq("classify_id", data.getClassifyId())
                    .eq("filling_model", data.getFillingModel())
                    .eq("is_only", "1")
                    .ne("id", data.getId())) > 0) {
                return AjaxResult.error("配置中已存在唯一字段");
            }
        }

        if (data.getIsOnly() == null) {
            data.setIsOnly("0");
        }
        if (data.getIsSort() == null) {
            data.setIsSort("0");
        }
        if (data.getIsMakeonly() == null) {
            data.setIsMakeonly("0");
        }
        if (data.getIsMust() == null) {
            data.setIsMust("0");
        }
        if (data.getIsVaguesearch() == null) {
            data.setIsVaguesearch("0");
        }
        if (data.getIsFastsearch() == null) {
            data.setIsFastsearch("0");
        }
        if (data.getIsmixSort() == null) {
            data.setIsmixSort("0");
        }
        if (data.getIsAutoinc() == null) {
            data.setIsAutoinc("0");
        }
        if (data.getIsKeep() == null) {
            data.setIsKeep("0");
        }
        if (data.getIsSearch() == null) {
            data.setIsSearch("0");
        }
        if (data.getIsShowedit() == null) {
            data.setIsShowedit("0");
        }
        if (data.getIsShowlist() == null) {
            data.setIsShowlist("0");
        }
        if (data.getFixedLeft() == null) {
            data.setFixedLeft("0");
        }
        return saveOrUpdate(data) ? AjaxResult.success("设置字段信息成功") : AjaxResult.error("设置字段信息失败");

    }

    @Override
    public AjaxResult delFieldConfig(String classifyId, String id) {
        try {
            this.remove(new QueryWrapper<FieldConfig>()
                    .eq("classify_id", classifyId)
                    .eq("id", id));
            return AjaxResult.success();
        } catch (Exception E) {
            return AjaxResult.error(E.getMessage());
        }
    }

    @Override
    public AjaxResult moveMetadataPosition(String id, String classifyId, String fillingModel, String action) {
        FieldConfig data = getOne(new QueryWrapper<FieldConfig>().eq("id", id).last("limit 1"));
        if (data == null) {
            return AjaxResult.error("没有找到该元数据的配置信息");
        }
        int nowIdx = data.getShowIdx();
        int objIdx = nowIdx;
        QueryWrapper qw = new QueryWrapper<FieldConfig>()
                .eq("classify_id", classifyId)
                .eq("filling_model", fillingModel)
                .last("limit 1");

        if ("0".equals(action)) {
            if (nowIdx < 1) {
                return AjaxResult.error("该元数据已经是排在最前面了");
            }
            qw.lt("show_idx", nowIdx);
            qw.orderByDesc("show_idx");
            objIdx = objIdx - 1;
        } else if ("1".equals(action)) {
            if (nowIdx >= count(new QueryWrapper<FieldConfig>()
                    .eq("classify_id", classifyId)
                    .eq("filling_model", fillingModel))) {
                return AjaxResult.error("该元数据已经是排在最后面了");
            }
            qw.gt("show_idx", nowIdx);
            qw.orderByAsc("show_idx");
            objIdx = objIdx + 1;
        }

        DataSourceTransactionManager tran = new DataSourceTransactionManager(jdbcTemplate.getDataSource());
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus update = tran.getTransaction(def);
        FieldConfig moveData = getOne(qw);
        if (moveData == null) {
            return AjaxResult.error("该元数据已经是排在最前面了");
        }
        moveData.setShowIdx(nowIdx);
        data.setShowIdx(objIdx);
        data.setEditIdx(objIdx);
        updateById(moveData);
        updateById(data);
        try {
            tran.commit(update);
            return AjaxResult.success("保存元数据设置成功");
        } catch (Exception e) {
            tran.rollback(update);
            return AjaxResult.error("保存元数据设置失败，错误信息：" + e.getMessage());
        }
    }

    @Override
    public List<FieldConfig> getFieldConfig(String classifyId, String codeModel) {
        return list(new QueryWrapper<FieldConfig>()
                .eq("classify_id", classifyId)
                .eq("filling_model", codeModel)
                .orderByAsc("show_idx"));
    }

    @Override
    public AjaxResult getParentField(String classifyId, String fillingModel) {
        List<FieldConfig> fieldList = list(new QueryWrapper<FieldConfig>()
                .eq("classify_id", classifyId)
                .eq("filling_model", fillingModel)
                .orderByAsc("show_idx"));
        Map<String, String> map = new LinkedHashMap<>();
        for (FieldConfig field : fieldList) {
            map.put(field.getFieldName(), field.getFieldTitle());
        }
        return AjaxResult.success(map);
    }

    @Override
    public String getOnlyField(String classifyId, String fillingModel) {
        FieldConfig data = getOne(new QueryWrapper<FieldConfig>()
                .eq("classify_id", classifyId)
                .eq("filling_model", fillingModel)
                .eq("is_only", "1")
                .last(" limit 1"));
        if (data != null) {
            return data.getFieldName();
        } else {
            return "";
        }
    }
}
